import datamodel
import logging
import utils

from google.appengine.ext import db

import area_crud
import utils

class Trip():
	def create(self, dispatcher):
		logging.info("create")
		dispatcher.modelObject.userId = dispatcher.userId
		dispatcher.modelObject.put()
		return dispatcher.modelObject

	def update(self, dispatcher):
		logging.info("update")
		tripDto = dispatcher.modelObject
		return tripDto

	def delete(self, dispatcher):
		logging.info("delete")
		areas = db.get(dispatcher.modelObject.areas)
		if areas:
			for deleteArea in areas:
				area_crud.Area().deleteArea(deleteArea,dispatcher.modelObject)
		dispatcher.modelObject.delete()

	def get(self, dispatcher):
		logging.info("get")
		if dispatcher.modelKey:
			logging.info("getting trip")
			myOutput = dict()
			myOutput["areas"] = db.get(dispatcher.modelObject.areas)
			myOutput["trip"] = dispatcher.modelObject
			return myOutput
		else:
			query = datamodel.Trip.all()
			if not dispatcher.isAdminData:
				query.filter('userId =', dispatcher.userId)
			else:
				logging.info("getting all trips for user")
			query.order('name')
			return query.fetch(100)
	
	def decode(self, decodeType, inputStr, inputObj, dispatcher):
		if inputObj == None:
			inputObj = datamodel.Trip()
		return utils.GqlDecoder().decode(inputStr, inputObj)

	def encode(self, decodeType, outputObj, dispatcher):
		return utils.GqlEncoder().encode(outputObj)
